/**
 * 性能监控工具
 * 监控应用性能、用户体验指标和错误日志
 */

/**
 * 性能监控器类
 */
class PerformanceMonitor {
	constructor() {
		this.metrics = {
			pageLoad: [],
			api: [],
			user: [],
			error: [],
			memory: [],
			network: []
		}
		this.startTime = Date.now()
		this.isMonitoring = true
		this.maxRecords = 1000 // 最大记录数
		
		this.init()
	}
	
	/**
	 * 初始化监控
	 */
	init() {
		this.setupErrorHandling()
		this.startMemoryMonitoring()
		this.setupNetworkMonitoring()
		this.loadStoredMetrics()
	}
	
	/**
	 * 设置错误处理
	 */
	setupErrorHandling() {
		// 全局错误处理
		if (typeof window !== 'undefined') {
			window.addEventListener('error', (event) => {
				this.recordError({
					type: 'javascript',
					message: event.message,
					filename: event.filename,
					lineno: event.lineno,
					colno: event.colno,
					stack: event.error?.stack
				})
			})
			
			window.addEventListener('unhandledrejection', (event) => {
				this.recordError({
					type: 'promise',
					message: event.reason?.message || 'Unhandled Promise Rejection',
					stack: event.reason?.stack
				})
			})
		}
		
		// 重写console.error以捕获错误
		const originalError = console.error
		console.error = (...args) => {
			this.recordError({
				type: 'console',
				message: args.join(' '),
				args: args
			})
			originalError.apply(console, args)
		}
	}
	
	/**
	 * 开始内存监控
	 */
	startMemoryMonitoring() {
		if (typeof performance !== 'undefined' && performance.memory) {
			setInterval(() => {
				if (this.isMonitoring) {
					this.recordMemoryUsage()
				}
			}, 30000) // 每30秒记录一次
		}
	}
	
	/**
	 * 设置网络监控
	 */
	setupNetworkMonitoring() {
		// 监控网络状态变化
		if (typeof navigator !== 'undefined' && navigator.connection) {
			navigator.connection.addEventListener('change', () => {
				this.recordNetworkChange()
			})
		}
	}
	
	/**
	 * 记录页面加载性能
	 * @param {string} pageName - 页面名称
	 * @param {number} startTime - 开始时间
	 * @param {number} endTime - 结束时间
	 */
	recordPageLoad(pageName, startTime, endTime = Date.now()) {
		const loadTime = endTime - startTime
		const metric = {
			id: this.generateId(),
			pageName,
			loadTime,
			timestamp: new Date().toISOString(),
			navigationType: this.getNavigationType(),
			deviceInfo: this.getDeviceInfo()
		}
		
		this.addMetric('pageLoad', metric)
		console.log(`页面加载: ${pageName} - ${loadTime}ms`)
	}
	
	/**
	 * 记录API调用性能
	 * @param {string} url - API地址
	 * @param {string} method - 请求方法
	 * @param {number} startTime - 开始时间
	 * @param {number} endTime - 结束时间
	 * @param {number} status - 响应状态码
	 * @param {boolean} success - 是否成功
	 */
	recordApiCall(url, method, startTime, endTime, status, success) {
		const responseTime = endTime - startTime
		const metric = {
			id: this.generateId(),
			url,
			method,
			responseTime,
			status,
			success,
			timestamp: new Date().toISOString(),
			networkType: this.getNetworkType()
		}
		
		this.addMetric('api', metric)
		
		if (!success || responseTime > 5000) {
			console.warn(`API性能警告: ${method} ${url} - ${responseTime}ms, 状态: ${status}`)
		}
	}
	
	/**
	 * 记录用户交互性能
	 * @param {string} action - 操作类型
	 * @param {string} element - 元素标识
	 * @param {number} startTime - 开始时间
	 * @param {number} endTime - 结束时间
	 */
	recordUserInteraction(action, element, startTime, endTime = Date.now()) {
		const responseTime = endTime - startTime
		const metric = {
			id: this.generateId(),
			action,
			element,
			responseTime,
			timestamp: new Date().toISOString(),
			pageName: this.getCurrentPageName()
		}
		
		this.addMetric('user', metric)
		
		if (responseTime > 100) {
			console.warn(`用户交互延迟: ${action} on ${element} - ${responseTime}ms`)
		}
	}
	
	/**
	 * 记录错误
	 * @param {Object} error - 错误信息
	 */
	recordError(error) {
		const errorMetric = {
			id: this.generateId(),
			...error,
			timestamp: new Date().toISOString(),
			pageName: this.getCurrentPageName(),
			userAgent: typeof navigator !== 'undefined' ? navigator.userAgent : '',
			url: typeof window !== 'undefined' ? window.location.href : ''
		}
		
		this.addMetric('error', errorMetric)
		console.error('性能监控记录错误:', errorMetric)
	}
	
	/**
	 * 记录内存使用情况
	 */
	recordMemoryUsage() {
		if (typeof performance !== 'undefined' && performance.memory) {
			const memory = performance.memory
			const metric = {
				id: this.generateId(),
				usedJSHeapSize: memory.usedJSHeapSize,
				totalJSHeapSize: memory.totalJSHeapSize,
				jsHeapSizeLimit: memory.jsHeapSizeLimit,
				usagePercentage: (memory.usedJSHeapSize / memory.jsHeapSizeLimit) * 100,
				timestamp: new Date().toISOString()
			}
			
			this.addMetric('memory', metric)
			
			if (metric.usagePercentage > 80) {
				console.warn(`内存使用率过高: ${metric.usagePercentage.toFixed(2)}%`)
			}
		}
	}
	
	/**
	 * 记录网络状态变化
	 */
	recordNetworkChange() {
		if (typeof navigator !== 'undefined' && navigator.connection) {
			const connection = navigator.connection
			const metric = {
				id: this.generateId(),
				effectiveType: connection.effectiveType,
				downlink: connection.downlink,
				rtt: connection.rtt,
				saveData: connection.saveData,
				timestamp: new Date().toISOString()
			}
			
			this.addMetric('network', metric)
			console.log('网络状态变化:', metric)
		}
	}
	
	/**
	 * 添加指标到集合
	 * @param {string} type - 指标类型
	 * @param {Object} metric - 指标数据
	 */
	addMetric(type, metric) {
		if (!this.metrics[type]) {
			this.metrics[type] = []
		}
		
		this.metrics[type].unshift(metric)
		
		// 限制记录数量
		if (this.metrics[type].length > this.maxRecords) {
			this.metrics[type] = this.metrics[type].slice(0, this.maxRecords)
		}
		
		// 定期保存到本地存储
		this.saveMetricsDebounced()
	}
	
	/**
	 * 获取性能报告
	 * @param {string} type - 指标类型
	 * @param {number} hours - 时间范围（小时）
	 * @returns {Object} 性能报告
	 */
	getPerformanceReport(type = null, hours = 24) {
		const cutoffTime = new Date(Date.now() - hours * 60 * 60 * 1000)
		
		if (type) {
			return this.analyzeMetrics(type, cutoffTime)
		} else {
			const report = {}
			Object.keys(this.metrics).forEach(metricType => {
				report[metricType] = this.analyzeMetrics(metricType, cutoffTime)
			})
			return report
		}
	}
	
	/**
	 * 分析指标数据
	 * @param {string} type - 指标类型
	 * @param {Date} cutoffTime - 截止时间
	 * @returns {Object} 分析结果
	 */
	analyzeMetrics(type, cutoffTime) {
		const metrics = this.metrics[type]?.filter(m => 
			new Date(m.timestamp) > cutoffTime
		) || []
		
		if (metrics.length === 0) {
			return { count: 0, message: '无数据' }
		}
		
		switch (type) {
			case 'pageLoad':
				return this.analyzePageLoadMetrics(metrics)
			case 'api':
				return this.analyzeApiMetrics(metrics)
			case 'user':
				return this.analyzeUserMetrics(metrics)
			case 'error':
				return this.analyzeErrorMetrics(metrics)
			case 'memory':
				return this.analyzeMemoryMetrics(metrics)
			case 'network':
				return this.analyzeNetworkMetrics(metrics)
			default:
				return { count: metrics.length, data: metrics }
		}
	}
	
	/**
	 * 分析页面加载指标
	 * @param {Array} metrics - 指标数据
	 * @returns {Object} 分析结果
	 */
	analyzePageLoadMetrics(metrics) {
		const loadTimes = metrics.map(m => m.loadTime)
		const pageStats = {}
		
		metrics.forEach(m => {
			if (!pageStats[m.pageName]) {
				pageStats[m.pageName] = []
			}
			pageStats[m.pageName].push(m.loadTime)
		})
		
		return {
			count: metrics.length,
			average: this.calculateAverage(loadTimes),
			median: this.calculateMedian(loadTimes),
			min: Math.min(...loadTimes),
			max: Math.max(...loadTimes),
			p95: this.calculatePercentile(loadTimes, 95),
			pageStats: Object.keys(pageStats).map(page => ({
				page,
				count: pageStats[page].length,
				average: this.calculateAverage(pageStats[page])
			}))
		}
	}
	
	/**
	 * 分析API指标
	 * @param {Array} metrics - 指标数据
	 * @returns {Object} 分析结果
	 */
	analyzeApiMetrics(metrics) {
		const responseTimes = metrics.map(m => m.responseTime)
		const successRate = metrics.filter(m => m.success).length / metrics.length
		const errorRate = 1 - successRate
		
		const statusCodes = {}
		metrics.forEach(m => {
			statusCodes[m.status] = (statusCodes[m.status] || 0) + 1
		})
		
		return {
			count: metrics.length,
			average: this.calculateAverage(responseTimes),
			median: this.calculateMedian(responseTimes),
			p95: this.calculatePercentile(responseTimes, 95),
			successRate: (successRate * 100).toFixed(2) + '%',
			errorRate: (errorRate * 100).toFixed(2) + '%',
			statusCodes,
			slowRequests: metrics.filter(m => m.responseTime > 3000).length
		}
	}
	
	/**
	 * 分析用户交互指标
	 * @param {Array} metrics - 指标数据
	 * @returns {Object} 分析结果
	 */
	analyzeUserMetrics(metrics) {
		const responseTimes = metrics.map(m => m.responseTime)
		const actionStats = {}
		
		metrics.forEach(m => {
			if (!actionStats[m.action]) {
				actionStats[m.action] = []
			}
			actionStats[m.action].push(m.responseTime)
		})
		
		return {
			count: metrics.length,
			average: this.calculateAverage(responseTimes),
			median: this.calculateMedian(responseTimes),
			slowInteractions: metrics.filter(m => m.responseTime > 100).length,
			actionStats: Object.keys(actionStats).map(action => ({
				action,
				count: actionStats[action].length,
				average: this.calculateAverage(actionStats[action])
			}))
		}
	}
	
	/**
	 * 分析错误指标
	 * @param {Array} metrics - 指标数据
	 * @returns {Object} 分析结果
	 */
	analyzeErrorMetrics(metrics) {
		const errorTypes = {}
		const errorPages = {}
		
		metrics.forEach(m => {
			errorTypes[m.type] = (errorTypes[m.type] || 0) + 1
			errorPages[m.pageName] = (errorPages[m.pageName] || 0) + 1
		})
		
		return {
			count: metrics.length,
			errorTypes,
			errorPages,
			recentErrors: metrics.slice(0, 10).map(m => ({
				type: m.type,
				message: m.message,
				timestamp: m.timestamp,
				page: m.pageName
			}))
		}
	}
	
	/**
	 * 分析内存指标
	 * @param {Array} metrics - 指标数据
	 * @returns {Object} 分析结果
	 */
	analyzeMemoryMetrics(metrics) {
		const usagePercentages = metrics.map(m => m.usagePercentage)
		const usedMemory = metrics.map(m => m.usedJSHeapSize)
		
		return {
			count: metrics.length,
			averageUsage: this.calculateAverage(usagePercentages).toFixed(2) + '%',
			maxUsage: Math.max(...usagePercentages).toFixed(2) + '%',
			averageMemory: this.formatBytes(this.calculateAverage(usedMemory)),
			maxMemory: this.formatBytes(Math.max(...usedMemory)),
			highUsageCount: metrics.filter(m => m.usagePercentage > 80).length
		}
	}
	
	/**
	 * 分析网络指标
	 * @param {Array} metrics - 指标数据
	 * @returns {Object} 分析结果
	 */
	analyzeNetworkMetrics(metrics) {
		const connectionTypes = {}
		const rttValues = metrics.map(m => m.rtt).filter(rtt => rtt > 0)
		const downlinkValues = metrics.map(m => m.downlink).filter(dl => dl > 0)
		
		metrics.forEach(m => {
			connectionTypes[m.effectiveType] = (connectionTypes[m.effectiveType] || 0) + 1
		})
		
		return {
			count: metrics.length,
			connectionTypes,
			averageRTT: rttValues.length > 0 ? this.calculateAverage(rttValues) : 0,
			averageDownlink: downlinkValues.length > 0 ? this.calculateAverage(downlinkValues) : 0,
			saveDataUsage: metrics.filter(m => m.saveData).length
		}
	}
	
	/**
	 * 计算平均值
	 * @param {Array} values - 数值数组
	 * @returns {number} 平均值
	 */
	calculateAverage(values) {
		if (values.length === 0) return 0
		return values.reduce((sum, val) => sum + val, 0) / values.length
	}
	
	/**
	 * 计算中位数
	 * @param {Array} values - 数值数组
	 * @returns {number} 中位数
	 */
	calculateMedian(values) {
		if (values.length === 0) return 0
		const sorted = [...values].sort((a, b) => a - b)
		const mid = Math.floor(sorted.length / 2)
		return sorted.length % 2 === 0 
			? (sorted[mid - 1] + sorted[mid]) / 2 
			: sorted[mid]
	}
	
	/**
	 * 计算百分位数
	 * @param {Array} values - 数值数组
	 * @param {number} percentile - 百分位
	 * @returns {number} 百分位数值
	 */
	calculatePercentile(values, percentile) {
		if (values.length === 0) return 0
		const sorted = [...values].sort((a, b) => a - b)
		const index = Math.ceil((percentile / 100) * sorted.length) - 1
		return sorted[Math.max(0, index)]
	}
	
	/**
	 * 格式化字节数
	 * @param {number} bytes - 字节数
	 * @returns {string} 格式化后的字符串
	 */
	formatBytes(bytes) {
		if (bytes === 0) return '0 Bytes'
		const k = 1024
		const sizes = ['Bytes', 'KB', 'MB', 'GB']
		const i = Math.floor(Math.log(bytes) / Math.log(k))
		return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
	}
	
	/**
	 * 获取导航类型
	 * @returns {string} 导航类型
	 */
	getNavigationType() {
		if (typeof performance !== 'undefined' && performance.navigation) {
			const type = performance.navigation.type
			switch (type) {
				case 0: return 'navigate'
				case 1: return 'reload'
				case 2: return 'back_forward'
				default: return 'unknown'
			}
		}
		return 'unknown'
	}
	
	/**
	 * 获取网络类型
	 * @returns {string} 网络类型
	 */
	getNetworkType() {
		if (typeof navigator !== 'undefined' && navigator.connection) {
			return navigator.connection.effectiveType || 'unknown'
		}
		return 'unknown'
	}
	
	/**
	 * 获取设备信息
	 * @returns {Object} 设备信息
	 */
	getDeviceInfo() {
		if (typeof uni !== 'undefined') {
			try {
				const systemInfo = uni.getSystemInfoSync()
				return {
					platform: systemInfo.platform,
					model: systemInfo.model,
					pixelRatio: systemInfo.pixelRatio
				}
			} catch (error) {
				return {}
			}
		}
		return {
			userAgent: typeof navigator !== 'undefined' ? navigator.userAgent : ''
		}
	}
	
	/**
	 * 获取当前页面名称
	 * @returns {string} 页面名称
	 */
	getCurrentPageName() {
		if (typeof getCurrentPages === 'function') {
			const pages = getCurrentPages()
			if (pages.length > 0) {
				return pages[pages.length - 1].route
			}
		}
		return typeof window !== 'undefined' ? window.location.pathname : 'unknown'
	}
	
	/**
	 * 生成唯一ID
	 * @returns {string} 唯一ID
	 */
	generateId() {
		return Date.now().toString(36) + Math.random().toString(36).substr(2)
	}
	
	/**
	 * 加载存储的指标
	 */
	loadStoredMetrics() {
		try {
			if (typeof uni !== 'undefined') {
				const stored = uni.getStorageSync('performanceMetrics')
				if (stored) {
					this.metrics = { ...this.metrics, ...stored }
				}
			}
		} catch (error) {
			console.error('加载性能指标失败:', error)
		}
	}
	
	/**
	 * 保存指标（防抖）
	 */
	saveMetricsDebounced() {
		if (this.saveTimeout) {
			clearTimeout(this.saveTimeout)
		}
		
		this.saveTimeout = setTimeout(() => {
			this.saveMetrics()
		}, 5000) // 5秒后保存
	}
	
	/**
	 * 保存指标到本地存储
	 */
	saveMetrics() {
		try {
			if (typeof uni !== 'undefined') {
				// 只保存最近的数据以节省存储空间
				const recentMetrics = {}
				Object.keys(this.metrics).forEach(type => {
					recentMetrics[type] = this.metrics[type].slice(0, 100)
				})
				uni.setStorageSync('performanceMetrics', recentMetrics)
			}
		} catch (error) {
			console.error('保存性能指标失败:', error)
		}
	}
	
	/**
	 * 清除所有指标
	 */
	clearMetrics() {
		this.metrics = {
			pageLoad: [],
			api: [],
			user: [],
			error: [],
			memory: [],
			network: []
		}
		this.saveMetrics()
	}
	
	/**
	 * 停止监控
	 */
	stopMonitoring() {
		this.isMonitoring = false
		this.saveMetrics()
	}
	
	/**
	 * 开始监控
	 */
	startMonitoring() {
		this.isMonitoring = true
	}
	
	/**
	 * 导出性能数据
	 * @returns {Object} 性能数据
	 */
	exportData() {
		return {
			metrics: this.metrics,
			report: this.getPerformanceReport(),
			exportTime: new Date().toISOString(),
			monitoringDuration: Date.now() - this.startTime
		}
	}
}

// 创建全局实例
const performanceMonitor = new PerformanceMonitor()

// 便捷方法
export const recordPageLoad = (pageName, startTime, endTime) => {
	performanceMonitor.recordPageLoad(pageName, startTime, endTime)
}

export const recordApiCall = (url, method, startTime, endTime, status, success) => {
	performanceMonitor.recordApiCall(url, method, startTime, endTime, status, success)
}

export const recordUserInteraction = (action, element, startTime, endTime) => {
	performanceMonitor.recordUserInteraction(action, element, startTime, endTime)
}

export const recordError = (error) => {
	performanceMonitor.recordError(error)
}

export const getPerformanceReport = (type, hours) => {
	return performanceMonitor.getPerformanceReport(type, hours)
}

export const clearMetrics = () => {
	performanceMonitor.clearMetrics()
}

export const exportPerformanceData = () => {
	return performanceMonitor.exportData()
}

// 导出监控器实例
export default performanceMonitor